package com.fzrskj.cloud.free.user.utils;

import com.fzrskj.cloud.free.core.enums.ProductTypeEnum;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.DoubleUtil;
import com.fzrskj.cloud.free.dic.bean.DicVipgrade;
import com.fzrskj.cloud.free.dic.dao.DicVipgradeDao;
import com.fzrskj.cloud.free.sys.bean.SysProductView;
import com.fzrskj.cloud.free.sys.utils.SysProductUtils;
import com.fzrskj.cloud.free.sys.utils.SysRunTimeLogUtils;
import com.fzrskj.cloud.free.user.bean.*;
import com.fzrskj.cloud.free.user.dao.UserAccountDao;
import com.fzrskj.cloud.free.user.dao.vo.AgentFinanceResultVo;
import com.fzrskj.cloud.free.user.dao.UserAccountDetailDao;
import com.fzrskj.cloud.free.user.dao.UserChargeDao;
import com.fzrskj.cloud.free.user.utils.func.FuncHandleUtisAgentHelper;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FuncHandleUtils {
	
	/**
	 * 在线处理
	 * @param orderId
	 * @return
	 */
	public String HandleOnLine(String orderId){
		String result="";
		JSONObject obj = new JSONObject();

		UserOrderUtils uoUtils = new UserOrderUtils();
		UserOrder userOrder = uoUtils.getUserOrder(orderId);
		if(userOrder==null){
			obj.put("code", "-1");
			obj.put("message", "订单["+orderId+"]不存在");
			return obj.toString();
		}

		if(userOrder.getHandleStatus().equals("Y")){
			obj.put("code", "-2");
			obj.put("message", "该订单已处理成功，请勿重复处理！");
			return obj.toString();
		}

		if(userOrder.getHandleStatus().equals("C")){
			obj.put("code", "-2");
			obj.put("message", "该订单正在处理，请勿重复处理！");
			return obj.toString();
		}
		if (ProductTypeEnum.DOMAIN.getTag().equals(userOrder.getProductClass())){
			if (Integer.valueOf(userOrder.getRegType()) == 6){
				if (uoUtils.checkIsPremiumDomain(userOrder)){
					obj.put("code", "-2");
					obj.put("message", "该订单域名价格异常，请联系管理员");
					return obj.toString();
				}
			}
		}

		//支付
		String payResult=OrderPay(userOrder);
		obj = JSONObject.fromObject(payResult);
		if(!"0".equals(obj.getString("code").trim())){
			userOrder.setHandleStatus("N");
			uoUtils.modUserOrder(userOrder);
			UserLogUtils.addLog(this, userOrder.getUserId(), "FinanceAccount", "财务记账失败，message=【"+obj.getString("message")+"】");
			return payResult;
		}

		//如果订单状态为未处理，更新为正在处理
		userOrder.setHandleStatus("C");
		uoUtils.modUserOrder(userOrder);

		//判断订单类型 add：开通 ，renew：续费，delete：删除，update：升级
		if(userOrder.getOrderType().equals("add")){
			result=OnLineCreate(userOrder);
		}else if(userOrder.getOrderType().equals("renew")){
			result=OnLineRenew(userOrder);
		}else if(userOrder.getOrderType().equals("delete")){
			result=OnLineDelete(userOrder);
		}else if(userOrder.getOrderType().equals("update")){
			result=OnLineUpdate(userOrder);
		}

		//开通成功，更新订单处理状态为处理成功否则失败。
		JSONObject jsonCode = JSONObject.fromObject(result);
		if("0".equals(jsonCode.getString("code").trim())) {
			userOrder.setHandleStatus("Y");
		} else {
			userOrder.setHandleStatus("N");
		}
		uoUtils.modUserOrder(userOrder);

		return result;
	}

	/**
	 * 在线开通
	 * @param userOrder
	 * @return
	 */
	private String OnLineCreate(UserOrder userOrder){
		String result="";
		//自定义产品
		if (ProductTypeEnum.DIY.getTag().equals(userOrder.getProductClass())) {
			UserDiyUtils diyUtils = new UserDiyUtils();
			return diyUtils.createInstance(userOrder);
		}
		Map<String, Object> error = new HashedMap();
		error.put("code", "-1");
		error.put("message", "未实现的接入商");
		return com.alibaba.fastjson.JSONObject.toJSONString(error);
	}

	/**
	 * 在线续费
	 * @param userOrder
	 * @return
	 */
	private String OnLineRenew(UserOrder userOrder){
		JSONObject obj = new JSONObject();

		if (ProductTypeEnum.DIY.equals(userOrder.getProductClass())) {
			UserDiyUtils diyUtils = new UserDiyUtils();
			return diyUtils.renewInstance(userOrder);
		}
		obj.put("code", "-1");
		obj.put("message", "不支持的续费类型或注册商");
		return obj.toString();
	}

	/**
	 * 在线删除
	 * @param userOrder
	 * @return
	 */
	private String OnLineDelete(UserOrder userOrder){
		JSONObject obj = new JSONObject();


		return obj.toString();
	}

	/**
	 * 在线升级
	 * @param userOrder
	 * @return
	 */
	private String OnLineUpdate(UserOrder userOrder){
		JSONObject obj = new JSONObject();
		try{
			if (ProductTypeEnum.DIY.equals(userOrder.getProductClass())) {

			}
			obj.put("code", "-1");
			obj.put("message", "不支持的升级类型或注册商");
		}catch (Exception e) {
			obj.put("code", "-1");
			obj.put("message", "升级失败");
			e.printStackTrace();
			StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            SysRunTimeLogUtils.addLog(this, userOrder.getUserId(), "OnLineUpdate", "发送报文=【"+userOrder.getOrderParam()+"】,接收异常=【"+sw.toString()+"】");
		}
		return obj.toString();
	}

	/**
	 * 订单支付
	 * @param userOrder
	 * @return
	 */
	public String OrderPay(UserOrder userOrder){
		String result="";
		JSONObject obj = new JSONObject();
		if("delete".equals(userOrder.getOrderType())){
			obj.put("code", "0");
			obj.put("message", "订单已支付");
			return obj.toString();
		}

		UserOrderUtils userOrderUtils=new UserOrderUtils();
		if(userOrder.getPayStatus().equals("Y")){
			obj.put("code", "0");
			obj.put("message", "订单已支付");
			return obj.toString();
		}

		//获取产品信息
		Map<String, Object> cdt = new HashMap<String, Object>();
		cdt.put("productCode", userOrder.getProductCode());
		SysProductUtils sysProductUtils=new SysProductUtils();
		SysProductView productView=sysProductUtils.querySysProduct(cdt);

		//订单类型
		String orderType="";
		if("add".equals(userOrder.getOrderType())) {
			orderType = "开通";
		} else if("renew".equals(userOrder.getOrderType())) {
			orderType = "续费";
		} else if("delete".equals(userOrder.getOrderType())) {
			orderType = "删除";
		} else if("update".equals(userOrder.getOrderType())) {
			orderType = "升级";
		}

		String financeDesc="";
		JSONObject param= JSONObject.fromObject(userOrder.getOrderParam());
		if(param.has("financeDesc")) {
			financeDesc = param.getString("financeDesc");
		} else {
			financeDesc = orderType;
		}

		//判断最终用户是否已支付。
		Map<String, Object> payCheck = new HashedMap();
		payCheck.put("status", 1);
		payCheck.put("userId", userOrder.getUserId());
		payCheck.put("voucherId", userOrder.getOrderId());
		UserAccountDetailDao detailDao = new UserAccountDetailDao();
		UserAccountDetailView view = detailDao.queryUadViewWithoutAgentId(payCheck);
		if (null == view) {
			//扣款并生成记账数据
			String remark="会员【"+userOrder.getUserName()+"】"+financeDesc+"产品【"+productView.getProductName()+"】，订单号：【"+userOrder.getOrderId()+"】，业务扣款【"+userOrder.getPayAmount()+"】";
			result=FinanceAccount(userOrder.getUserName(),300,remark,userOrder.getOrderId(),"","",userOrder.getPayAmount());
			obj= JSONObject.fromObject(result);
		} else {
			obj.put("code", "0");
		}


		if("0".equals(obj.getString("code").trim())){
			UserAccountDao accountDao = new UserAccountDao();
			UserAccount account = accountDao.getUserAccountWithoutAgent(userOrder.getUserId());
			Boolean dealAgentOrderPay = true;
			if (account.getAgentId() > 0) {
				AgentFinanceResultVo agentFinanceResultVo = FuncHandleUtisAgentHelper.agentOrderPay(userOrder, productView, account.getAgentId());
				dealAgentOrderPay = agentFinanceResultVo.getResult();
				if (!dealAgentOrderPay) {
					obj.put("message", agentFinanceResultVo.getMessage());
				}
			}

			if (dealAgentOrderPay) {
				obj.put("code", "0");
				obj.put("message", "扣款成功");

				//付款处理成功更新付款状态为已付款
				userOrder.setPayStatus("Y");
				userOrderUtils.modUserOrder(userOrder);
			} else {
				obj.put("code", "-1");
			}
		}else{
			obj.put("code", "-1");
			obj.put("message", obj.getString("message").trim());
		}
		return obj.toString();
	}

	/**
	 * 财务记账.
	 */
	public String FinanceAccount(String userName,int itemId,String remark,String voucherId,String bankCode,String billno,double amount){
		return FinanceAccount(userName,itemId,remark,voucherId,bankCode,billno,amount,userName);
	}

	public String FinanceAccount(String userName,int itemId,String remark,String voucherId,String bankCode,String billno,double amount,String optName){
		return this.FinanceAccount(userName, itemId, remark, voucherId, bankCode, billno, amount, optName, CloudContextUtils.getAgentId());
	}

	//财务记账
	public String FinanceAccount(String userName,int itemId,String remark,String voucherId,String bankCode,String billno,double amount,String optName, Integer agentId){
		JSONObject obj = new JSONObject();
		if(amount<0){
			obj.put("code", "-1");
			obj.put("message", "发生金额不能为负数");
			return obj.toString();
		}

		synchronized(FuncHandleUtils.class){
			UserAccountUtils uaUtils = new UserAccountUtils();
			UserAccount ua=uaUtils.queryAccountByName(userName, agentId);
			if(ua==null){
				obj.put("code", "-1");
				obj.put("message", "用户["+userName+"]不存在");
				return obj.toString();
			}

			if(itemId==200 || itemId==300){
				if(ua.getBalance()<amount){
					obj.put("code", "-1");
					obj.put("message", "操作失败，余额不足");
					return obj.toString();
				}
			}

			double balance=ua.getBalance();
			switch(itemId){
				case 100:
					//balance+=amount;
					balance = DoubleUtil.add(balance, amount);
					break;
				case 200:
					//balance-=amount;
					balance = DoubleUtil.sub(balance, amount);
					break;
				case 300:
					//balance-=amount;
					balance = DoubleUtil.sub(balance, amount);
					break;
				case 400:
					//balance+=amount;
					balance = DoubleUtil.add(balance, amount);
					break;
				case 500:
					//balance+=amount;
					balance = DoubleUtil.add(balance, amount);
					break;
				case 600:
					//balance-=amount;
					balance = DoubleUtil.sub(balance, amount);
					break;
			}

			if(balance<0) {
				balance = 0;
			}

			int ret=uaUtils.updateBlance(ua.getUserId(), ua.getUserName(), balance, agentId);
			if(ret>0){
				//插入记账数据
				UserAccountDetail entity = new UserAccountDetail();
				entity.setSnId("SN"+String.valueOf((new Date()).getTime()));
				entity.setUserId(ua.getUserId());
				entity.setUserName(ua.getUserName());
				entity.setItemId(itemId);
				entity.setRemark(remark);
				entity.setVoucherId(voucherId);
				entity.setBankCode(bankCode);
				entity.setBillno(billno);
				entity.setAmount(amount);
				entity.setBalance(balance);
				entity.setOperator(optName);
				entity.setRegDate(new Date());
				entity.setStatus(1);
				entity.setAgentId(agentId);

				UserAccountDetailUtils uadUtils=new UserAccountDetailUtils();
			    ret=uadUtils.addUserAccountDetail(entity);
				if(ret>0){
					obj.put("code", "0");
				}
			}else{
				obj.put("code", "-1");
				obj.put("message", "记账失败");
				UserLogUtils.addLog(this, ua.getUserId(), "请求参数：金额["+amount+"]，用户名["+userName+"]，记账项["+itemId+"]");
			}
		}

		return obj.toString();
	}

	/**
	 * 共用账本返款.
	 * @param agentId
	 * @param lastAgentId
	 * @param orderId
	 * @param bankCode
	 * @param billNo
	 * @param amount
	 * @param optName
	 * @param remark
	 */
	public void refundsForAgent(Integer agentId, Integer lastAgentId, String orderId, String bankCode, String billNo, Double amount, String optName, String remark) {
		if (agentId.equals(lastAgentId)) {
			return;
		}

		//为本次代理做款
		UserAccountView accountView = UserAccountUtils.getUserAccountWithoutAgent(agentId);
		this.FinanceAccount(accountView.getUserName(),100, "为代理返款，来自：[" + remark + "]", orderId,bankCode,billNo, amount, optName, accountView.getAgentId());

		//为再上一级做款
		this.refundsForAgent(accountView.getAgentId(), lastAgentId, orderId, bankCode, billNo, amount, optName, remark);
	}

	/**
	 * 更新会员等级
	 * @param orderId
	 * @return
	 */
	public void uptVipgrade(String orderId){
		if(CStrTool.isBlankStr(orderId)){
			return ;
		}
		int oldleveId = 0;
		int newleveId = 0;
		String newLevelCode =null;
		//获取充值订单信息
		UserChargeDao uchargedao = new UserChargeDao();
		UserCharge ucharge = uchargedao.queryUserChargeByOederId(orderId);
		if(ucharge==null) {
			UserLogUtils.addLog(this, 0, "订单【" + orderId + "】查询失败");
		}

		//获取充值总金额
		double account = uchargedao.queryUserChargeAmount(ucharge.getUserId(), ucharge.getAgentId());
		uchargedao.dispose();

		//获取用户信息
		UserAccountDao uaccountdao = new UserAccountDao();
		UserAccountView ua = uaccountdao.queryUserAccountWithoutAgent(ucharge.getUserId());
		if(ua==null) {
			UserLogUtils.addLog(this, ucharge.getUserId(), "查询会员【" + ucharge.getUserId() + "】信息失败");
		}

		//获取会员等级列表
		DicVipgradeDao vipgradedao= new DicVipgradeDao();
		List<DicVipgrade> vipgradelist = vipgradedao.querySysVipgrade(ucharge.getUserId());
		vipgradedao.dispose();

		//判断是否要修改会员等级
		for(DicVipgrade dicvip: vipgradelist){
			//获取会员等级的ID
			if(CStrTool.isBlankStr(ua.getLevelCode())){
				oldleveId = 1;
			}else if(dicvip.getLevelCode().equals(ua.getLevelCode())){
				oldleveId = dicvip.getId();
			}

			if(dicvip.getId() > oldleveId && oldleveId > 0 && dicvip.getMinCharge() <= account && dicvip.getMaxCharge() > 0){
				newleveId = dicvip.getId();
				newLevelCode = dicvip.getLevelCode();
			}
		}

		//修改会员等级
		if(newleveId > oldleveId && oldleveId > 0  && !(CStrTool.isBlankStr(newLevelCode))){
			int ret=uaccountdao.uptAccountBylevelCode(ua.getUserName(), ua.getUserId(), newLevelCode, ucharge.getAgentId());
			if(ret>0) {
				UserLogUtils.addLog(this, ua.getUserId(), "将会员【" + ua.getUserName() + "】的等级，修改为【" + newLevelCode + "】", ucharge.getAgentId());
			} else {
				UserLogUtils.addLog(this, ua.getUserId(), "修改会员【" + ua.getUserName() + "】等级失败", ucharge.getAgentId());
			}
		}	
		uaccountdao.dispose();
	}
}
